package com.yc.autouser.service;

import com.yc.common.expection.RedisException;
import com.yc.common.expection.ServerException;
import com.yc.common.utils.RedisUtils;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
@Service
public class EmailCodeService {
    @Autowired
    private RedisUtils redisUtils;
    public void emailCodeSend(String email, String emailCode) {


        try {

            //redisTemplate.opsForValue().set(email,emailCode);//设置邮箱验证码5分钟内有效
//            redisTemplate.opsForValue().set(email, emailCode, 5, TimeUnit.MINUTES);
            redisUtils.set(email,emailCode,5,TimeUnit.MINUTES);
            HtmlEmail mail = new HtmlEmail();
            /*发送邮件的服务器 126邮箱为smtp.126.com,163邮箱为163.smtp.com，QQ为smtp.qq.com*/
            mail.setHostName("smtp.qq.com");
            /*不设置发送的消息有可能是乱码*/
            mail.setCharset("UTF-8");
            /*IMAP/SMTP服务的密码*/
            mail.setAuthentication("604276934@qq.com", "cyodcqsyosdobefb");
            /*发送邮件的邮箱和发件人*/
            mail.setFrom("604276934@qq.com", "邮箱测试");
            /*使用安全链接*/
            mail.setSSLOnConnect(true);
            /*接收的邮箱*/
            mail.addTo(email);
            /*验证码*/
            String code = emailCode;
            /*设置邮件的主题*/
            mail.setSubject("注册验证码");
            /*设置邮件的内容*/
            mail.setMsg("尊敬的用户:你好! 注册验证码为:" + code + "(有效期为5分钟)");
            mail.send();//发送
        } catch (RedisException e) {
            throw new RedisException("redis存储错误");
        } catch (EmailException e) {
            throw new ServerException("验证码发送异常");
        }
    }
}
